package com.greathf.hf_ywgl.controller;

import com.greathf.hf_ywgl.config.RequestConfig;
import com.greathf.hf_ywgl.pojo.HF_Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
public class WxsController {

    @Autowired
    public RequestConfig requestConfig;

    @Autowired
    private RestTemplate restTemplate;

    @PostMapping("/extgw/doInvoke")
    public HF_Result doInvoke(String head, String data, String files, String sign) {
        HF_Result hf_result = new HF_Result();
        //设置超时
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        //读取超时10秒,默认无限限制,单位：毫秒
        requestFactory.setConnectTimeout(requestConfig.connectTimeout);
        //连接超时10秒，默认无限制，单位：毫秒
        requestFactory.setReadTimeout(requestConfig.readTimeout);
        List<String> slhResults = new ArrayList<>();
        HttpHeaders headers = new HttpHeaders();
        //设置编码
        headers.add("Content-Type", "application/x-www-form-urlencoded");

        // 参数集合
        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        map.add("head", head);
        map.add("data", data);
        map.add("files", files);
        map.add("sign", sign);

        log.info("doInvoke入参:" + map.toString());

        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(map, headers);
        ResponseEntity<String> response;

        try {
            response = restTemplate.postForEntity(requestConfig.url, requestEntity, String.class);
            log.info("返回状态：" + response.getStatusCode());
            String slhJson = response.getBody();
            log.info("返回数据:" + slhJson);

            ObjectMapper objectMapper = new ObjectMapper();
            hf_result = objectMapper.readValue(slhJson, HF_Result.class);

        } catch (Exception ex) {
            hf_result = HF_Result.error("0", ex.getMessage());
        }
        return hf_result;
    }
}
